package thread.lock;



import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 真香
 * @create 2021-06-04 18:44
 */
public class TestLock {

    public static void main(String[] args){

        ticket ticket = new ticket();



        new Thread(ticket).start();
        new Thread(ticket).start();
        new Thread(ticket).start();
    }

}


class ticket implements Runnable {


    private int ticketNums = 10;


    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        buyTicket();
    }

    public void  buyTicket()  {

        while (true) {
            try {
                lock.lock();
                if (ticketNums < 0) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--+"张票");
            }finally {
                lock.unlock();
            }

        }

    }



}
